<template>
  <div class="drage-able">
    <transition-group class="container" name="sort">
      <div
        class="app-item"
        v-for="app in customApps"
        :key="app.id"
        :draggable="true"
        @dragstart="dragstart(app)"
        @dragenter="dragenter(app,$event)"
        @dragend="getDragend(customApps, 'customer', $event)"
      >
        <div>
          <div class="ellipsis">{{app.name}}</div>
        </div>
      </div>
    </transition-group>
  </div>
</template>

<script>
export default {
  data() {
    return {
      oldData: [],
      newData: [],
      customApps: [
        { name: "1", id: 1 },
        { name: "2", id: 2 },
        { name: "3", id: 3 },
        { name: "4", id: 4 },
        { name: "5", id: 5 }
      ],
      dragStartId: "",
      dragEndId: ""
    };
  },
  methods: {
    dragstart(value) {
      console.log(value, "kkkk");
      this.oldData = value;
      this.dragStartId = value.id;
    },
    dragenter(value) {
      this.newData = value;
      this.dragEndId = value.id;
    },
    getDragend(listData, type) {
      if (this.oldData !== this.newData) {
        let oldIndex = listData.indexOf(this.oldData);
        let newIndex = listData.indexOf(this.newData);
        let newItems = [...listData];
        // 删除之前DOM节点
        newItems.splice(oldIndex, 1);
        // 在拖拽结束目标位置增加新的DOM节点
        newItems.splice(newIndex, 0, this.oldData);
        // 每次拖拽结束后，将拖拽处理完成的数据，赋值原数组，使DOM视图更新，页面显示拖拽动画
        this.customApps = newItems;
        console.log(this.customApps, "ljsdlfkj");
        // 每次拖拽结束后调用接口时时保存数据
        // Api(this.dragStartId, this.dragEndId).then(res => {});
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.drage-able {
  margin: 200px auto;
  padding-left: 100px;
}
.app-item {
  height: 40px;
  line-height: 40px;
  background-color: yellow;
  margin-bottom: 10px;
}
.sort-move {
  transition: transform 1s;
}
</style>
